package com.spider.silence.output;

import com.google.common.collect.Lists;
import com.spider.silence.utils.PropertiesUtil;

import java.io.IOException;
import java.util.LinkedList;

/**
 * @author 夏茂轩
 * @package com.spider.silence.output
 * @Date 2017/6/21 9:46
 */
public class FileWriterPool {


    private static FileWriterPool  instance= new FileWriterPool();
    protected LinkedList<FileWriter> pool = Lists.newLinkedList();

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:18
     * @description FTPWriterPool,初始化多个FTPWriter添加到池中
     */
    private   FileWriterPool(){
        synchronized (pool){
            for(int i = 0; i<Integer.valueOf(PropertiesUtil.getVal("main.file.writer.pool.size")); i++){
                FileWriter writer =new FileWriter();
                pool.add(writer);
            }
            pool.notifyAll();
        }

    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:18
     * @description FTPWriterPool 单例
     * @return 返回初始化完成后的 FTPWriterPool
     */
    public  static FileWriterPool getInstance(){
        if(instance==null){
            instance=new FileWriterPool();
        }
        return  instance;
    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:19
     * @description 返还使用完成的 FTPWriter
     * @param writer
     */
    public  void releaseWriter(FileWriter writer) {
        if (writer != null) {
            synchronized (pool) {
                pool.addLast(writer);
                pool.notifyAll();
            }
        }
    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:20
     * @description 获取一个FTPWriter,该方法为阻塞方法***
     * @return FTPWriter
     * @throws InterruptedException 中断异常
     */
    public  FileWriter fetchWriter() throws InterruptedException {
        synchronized (pool){
            while (pool.isEmpty()){
                pool.wait();
            }
            return pool.removeFirst();
        }
    }

    /**
     * @author 夏茂轩
     * @date 2017/1/15 22:21
     * @description 清空池
     */
    public void empty(){
        pool=Lists.newLinkedList();
    }

    public static void main(String[] args) {

    }
}
